# # -*- encoding: utf-8 -*-
# # -----------------------------------------------------------------------------
# #
# #  FreeType high-level python API - Copyright 2020-2020 Nicolas P. Rougier
# #  Distributed under the terms of the new BSD license.
# #
# # -----------------------------------------------------------------------------
# '''
# @Author  :   xichao
# @License :   Copyright (c) 2020, xichao
# @Contact :   kouxichao@qq.com
# @Software:   \\10.12.13.161\share\kxc\disk_2t\kxc\LayoutGen
# @File    :   font_test.py
# @Time    :   2020年11月20日 13:43:24 星期五
# @Desc    :
# '''
# from freetype import *
# import numpy as np
# from PIL import Image


# def render(filename = "Vera.ttf", hinting = (False,False), gamma = 1.5, lcd=False):
#     text = "A Quick Brown Fox Jumps Over The Lazy Dog 0123456789"
#     word = "abcdefghijklmnopqrstuvwxyz01234567 a b c d e f g h i j k l m n o p q r s t u v w x y z 0 1 2 3 4 5 6 7 8 9 "

#     W,H,D = 680, 280, 1
#     Z = np.zeros( (H,W), dtype=np.ubyte )
#     face = Face(filename)
#     print(filename)
#     pen = Vector(5*64, (H-10)*64)
#     # print("face.num_fixed_sizes: ", face.num_fixed_sizes)
#     # print("face.available_sizes: ", face.available_sizes)
#     # print("face.num_glyphs: ", face.num_glyphs)
#     # print("face.units_per_EM: ", face.units_per_EM)
#     # print("face.face_flags: ", face.face_flags)
#     # face.set_char_size( 32 * 64, 0, 0, 72 )
#     # face.load_char("A") #FT_LOAD_NO_HINTING | FT_LOAD_RENDER
#     # kerning = face.get_kerning( previous, current, FT_KERNING_UNSCALED )
#     # pen.x += kerning.x
#     # glyph = face.glyph
#     # bitmap = glyph.bitmap
#     # print("glyph.format: ",  FT_GLYPH_FORMAT_OUTLINE, " ", glyph.format) 
#     flags = FT_LOAD_RENDER 
#     if hinting[1]: flags |= FT_LOAD_FORCE_AUTOHINT
#     else:          flags |= FT_LOAD_NO_HINTING
#     if hinting[0]: hres, hscale = 72,    1.0
#     else:          hres, hscale = 72*10, 0.1
#     if lcd:
#         flags |= FT_LOAD_TARGET_LCD
#         Z = np.zeros( (H,W,3), dtype=np.ubyte )
#         try:
#             set_lcd_filter( FT_LCD_FILTER_DEFAULT )
#         except:
#             pass


#     for size in range(9,23):
#         face.set_char_size( size * 64, 0, hres, 72 )
#         matrix = Matrix( int((hscale) * 0x10000), int((0.0) * 0x10000),
#                          int((0.0)    * 0x10000), int((1.0) * 0x10000) )
#         previous = 0
#         pen.x = 0#5*64
#         for current in text:
#             face.set_transform( matrix, pen )
#             face.load_char( current, flags)
#             kerning = face.get_kerning( previous, current, FT_KERNING_UNSCALED )
#             pen.x += kerning.x
#             glyph = face.glyph
#             bitmap = glyph.bitmap
#             x, y = glyph.bitmap_left, glyph.bitmap_top
#             w, h, p = bitmap.width, bitmap.rows, bitmap.pitch
#             buff = np.array(bitmap.buffer, dtype=np.ubyte).reshape((h,p))
#             if lcd:
#                 Z[H-y:H-y+h,x:x+w/3].flat |= buff[:,:w].flatten()
#             else:
#                 Z[H-y:H-y+h,x:x+w].flat |= buff[:,:w].flatten()
#             pen.x += glyph.advance.x
#             previous = current
#         pen.y -= (size+4)*64

#     # Gamma correction
#     Z = (Z/255.0)**(gamma)
#     Z = ((1-Z)*255).astype(np.ubyte)
#     if lcd:
#         I = Image.fromarray(Z, mode='RGB')
#     else:
#         I = Image.fromarray(Z, mode='L')

#     name = filename.split('.')[-2]
#     filename = 'font_test/%s-gamma(%.1f)-hinting(%d,%d)-lcd(%d).png' % (name,gamma,hinting[0],hinting[1],lcd)
#     I.save(filename)



# if __name__ == '__main__':
#     fontSet = []
#     fontPath = "./font/en"
#     for _, _, filenames in os.walk(fontPath):
#         for filename in filenames:
#             if filename.endswith('ttf'):
#                 fontSet.append(filename)
#     imageNum = len(fontSet)
#     for i in range(imageNum):
#         render(os.path.join(fontPath, fontSet[i]), (0,1), 1.25, True)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
#
#  FreeType high-level python API - Copyright 2011-2015 Nicolas P. Rougier
#  Distributed under the terms of the new BSD license.
#
# -----------------------------------------------------------------------------
from freetype import *
import numpy as np
from PIL import Image

def render(filename = "Vera.ttf", hinting = (False,False), gamma = 1.5, lcd=False):
    text = "A Quick Brown Fox Jumps Over The Lazy Dog 0123456789"

    face = Face(filename)

    # print("face.has_horizontal ", face.has_horizontal)
    print(filename, " face.has_vertical ", face.has_vertical)
    W,H,D = 680, 280, 1
    Z = np.zeros( (H,W), dtype=np.ubyte )
    face = Face(filename)
    pen = Vector(5*64, (H-10)*64)

    flags = FT_LOAD_RENDER
    if hinting[1]: flags |= FT_LOAD_FORCE_AUTOHINT
    else:          flags |= FT_LOAD_NO_HINTING
    if hinting[0]: hres, hscale = 72,    1.0
    else:          hres, hscale = 72*10, 0.1
    if lcd:
        flags |= FT_LOAD_TARGET_LCD
        Z = np.zeros( (H,W,3), dtype=np.ubyte )
        try:
            set_lcd_filter( FT_LCD_FILTER_DEFAULT )
        except:
            pass


    glyph = face.glyph
    bitmap = glyph.bitmap

    for size in range(9,23):
        face.set_char_size( size * 64, 0, hres, 72 )
        matrix = Matrix( int((hscale) * 0x10000), int((0.0) * 0x10000),
                         int((0.0)    * 0x10000), int((1.0) * 0x10000) )
        previous = 0
        pen.x = 5*64
        for current in text:
            face.set_transform( matrix, pen )
            face.load_char( current)#, flags)
            kerning = face.get_kerning( previous, current, FT_KERNING_UNSCALED )
            pen.x += kerning.x
            # glyph = face.glyph
            # bitmap = glyph.bitmap
            x, y = glyph.bitmap_left, glyph.bitmap_top
            w, h, p = bitmap.width, bitmap.rows, bitmap.pitch
            buff = np.array(bitmap.buffer, dtype=np.ubyte).reshape((h,p))
            if lcd:
                Z[H-y:H-y+h,x:x+w/3].flat |= buff[:,:w].flatten()
            else:
                print(x)
                Z[H-y:H-y+h,x:x+w].flat |= buff[:,:w].flatten()
            pen.x += glyph.advance.x
            previous = current
        pen.y -= (size+4)*64

    # Gamma correction
    Z = (Z/255.0)**(gamma)
    Z = ((1-Z)*255).astype(np.ubyte)
    if lcd:
        I = Image.fromarray(Z, mode='RGB')
    else:
        I = Image.fromarray(Z, mode='L')

    name = filename.split('.')[-1]
    filename = './font_test/%s-gamma(%.1f)-hinting(%d,%d)-lcd(%d).png' % (name,gamma,hinting[0],hinting[1],lcd)
    I.save(filename)



if __name__ == '__main__':
    fontSet = []
    fontPath = "./font/en_title"
    for _, _, filenames in os.walk(fontPath):
        for filename in filenames:
            if filename.endswith('ttf'):
                fontSet.append(filename)
    imageNum = len(fontSet)
    # for i in range(imageNum):
    render(os.path.join(fontPath, fontSet[0]), (0,0), 1.25, False)
    
    # render('Vera.ttf', (0,1), 1.25, True)